<?php
/**
 * Created by PhpStorm.
 * User: sunny
 * 尽人事，听天命
 * Date: 2017/6/26
 * Time: 22:53
 */
namespace app\mobile\controller;

class Login extends Base{
    public function index(){
        if($_GET['qrcode_id']){
            $qrcode_id = $_GET['qrcode_id'];
        }
        if($this->is_wexin_browser){
            $url=config('SITE_URL').'/mobile/Login/weixin?qrcode_id='.$qrcode_id;
            return redirect($url);
        }
    }
    public function weixin(){
        $qrcode_id=!empty($_GET['qrcode_id']) ? $_GET['qrcode_id']:0;
        $_SESSION['weixin']['qrcode_id'] = $qrcode_id;
        $_SESSION['weixin']['state']   = md5(uniqid());
        $customeUrl = config('SITE_URL').'/mobile/Login/weixinBack?qrcode_id='.$qrcode_id;
        $oauthUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('THINK_SDK_WEIXIN.APP_KEY').'&redirect_uri='.urlencode($customeUrl).'&response_type=code&scope=snsapi_userinfo&state='.$_SESSION['weixin']['state'].'#wechat_redirect';
        return redirect($oauthUrl);
    }
    public function weixinBack(){
        if (isset($_GET['code'])){
            if(isset($_SESSION['weixin']['state'])) {
                unset($_SESSION['weixin']['state']);
            }
            if(isset($_GET['qrcode_id'])){
                $qrcode_id=$_GET['qrcode_id'];
            }
            import('Net.Http');
            $http = new \Http();
            $return = $http->curlGet('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('THINK_SDK_WEIXIN.APP_KEY').'&secret='.config('THINK_SDK_WEIXIN.APP_SECRET').'&code='.$_GET['code'].'&grant_type=authorization_code');
            $jsonrt = json_decode($return,true);
            if(isset($jsonrt['errcode'])){
                import('Wechat.GetErrorMsg');
                $error_msg_class = new \GetErrorMsg();
                return $this->returnJson('授权发生错误：'.$error_msg_class->wx_error_msg($jsonrt['errcode']),0);
            }
            $return = $http->curlGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$jsonrt['access_token'].'&openid='.$jsonrt['openid'].'&lang=zh_CN');
            $jsonrt = json_decode($return,true);
            if (isset($jsonrt['errcode'])) {
                import('Wechat.GetErrorMsg');
                $error_msg_class = new \GetErrorMsg();
                return $this->returnJson('授权发生错误：'.$error_msg_class->wx_error_msg($jsonrt['errcode']),0);
            }
//            /*优先使用 unionid 登录*/
//            if(!empty($jsonrt['unionid'])){
//               $this->autoLogin('union_id',$jsonrt['unionid']);
//            }
            /*再次使用 openid 登录*/
           if($res=$this->autoLogin('third_id',$jsonrt['openid'],$qrcode_id)){
               return $res;
           }
            /*注册用户*/
            $data_user = array(
                'third_id' 	=> $jsonrt['openid'],
                'username' 	=> $jsonrt['nickname'],
                'sex' 		=> $jsonrt['sex'],
                'province' 	=> $jsonrt['province'],
                'city' 		=> $jsonrt['city'],
                'avatar' 	=> $jsonrt['headimgurl'],
            );
            $_SESSION['weixin']['user'] = $data_user;
           return $this->weixinNoBind($qrcode_id);
        }else{
            return $this->returnJson('访问异常！请重新登录。',0);
        }
    }

    /**
     * 自动登录
     * @param $field
     * @param $value
     * created by sunnier<xiaoyao_xiao@126.com>
     */
    protected function autoLogin($field,$value,$qrcode_id=0){
        $result = model('Member')->autoRegLogin($field,$value);
        if(empty($result['error_code'])){
            $url=config('SITE_URL')."/mobile/WechatBind/regWechatLogin?qrcode_id=".$qrcode_id.'&uid='.$result['user']['id'];
            return redirect($url);
        }else if($result['error_code'] && $result['error_code'] != 1001){
            return false;
        }
    }

    /**
     * 微信不绑定手机号自动登录
     * created by sunnier<xiaoyao_xiao@126.com>
     */
    public function weixinNoBind($qrcode_id){
        if(empty($_SESSION['weixin']['user'])){
            return $this->returnJson('微信授权失效，请重新登录！',0);
        }
        $reg_result = model('Member')->autoReg($_SESSION['weixin']['user']);
        if($reg_result['error_code']){
           return  $this->returnJson($reg_result['msg'],0);
        }else{
            $login_result = model('Member')->autoRegLogin('third_id',$_SESSION['weixin']['user']['third_id']);
            if($login_result['error_code']){
                return $this->returnJson($login_result['msg'],0);
            }else{
                $url=config('SITE_URL')."/mobile/WechatBind/regWechatLogin?qrcode_id=".$qrcode_id.'&uid='.$login_result['user']['id'];
                return redirect($url);
            }
        }
    }
}